package com.txc.openfeign.config;


import cn.hutool.core.util.ObjectUtil;
import feign.Logger;
import feign.RequestInterceptor;
import feign.codec.Decoder;
import feign.optionals.OptionalDecoder;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.support.HttpMessageConverterCustomizer;
import org.springframework.cloud.openfeign.support.ResponseEntityDecoder;
import org.springframework.cloud.openfeign.support.SpringDecoder;
import org.springframework.context.annotation.Bean;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import jakarta.servlet.http.HttpServletRequest;
import java.util.Enumeration;

import static com.txc.common.global.constant.StrConstant.CONTENT_LENGTH;

/**
 * @ClassName: FeignConfig
 * @Author: TXC
 * @Date: 2023-08-08 23:23
 **/
public class DefaultFeignConfig {
    @Bean
    public Logger.Level feignLoggerLevel() {
        return Logger.Level.FULL;
    }

    @Bean
    public RequestInterceptor requestInterceptor() {
        return requestTemplate -> {
            ServletRequestAttributes attributes =
                    (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (ObjectUtil.isNotNull(attributes)) {
                HttpServletRequest request = attributes.getRequest();
                Enumeration<String> headerNames = request.getHeaderNames();
                String name;
                // 将原有请求中的header，数据转移至新的请求中
                if (ObjectUtil.isNotNull(headerNames)) {
                    while (headerNames.hasMoreElements()) {
                        name = headerNames.nextElement();
                        String values = request.getHeader(name);
                        if (!name.equalsIgnoreCase(CONTENT_LENGTH)) {
                            requestTemplate.header(name, values);
                        }
                    }
                }
            }
        };
    }

    @Bean
    public Decoder feignDecoder(ObjectFactory<HttpMessageConverters> msgConverters,
                                ObjectProvider<HttpMessageConverterCustomizer> customizers) {
        // 自定义feign的解析器
        // OptionalDecoder(response,type) -> ResponseEntityDecoder(response,type) -> 自定义Decoder(response,type)
        FeignResponseDecoder feignResponseDecoder = new FeignResponseDecoder(
                new SpringDecoder(msgConverters, customizers));
        ResponseEntityDecoder responseEntityDecoder = new ResponseEntityDecoder(feignResponseDecoder);
        return new OptionalDecoder(responseEntityDecoder);
    }
}
